﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using WeifenLuo.WinFormsUI.Docking;
using System.Reflection;
using WeifenLuo.WinFormsUI.Docking;
using WHC.Security.Entity;
using WHC.Security.DALSQL;


namespace CKNetFrameWork
{
    public partial class Frm_Main : Form
    {
        public static HelpNavigator m_Navigator = HelpNavigator.Topic;
        public static string m_strHelpPath = Application.StartupPath + @"\TrainingMis.chm";
        private Frm_MainToolWindow mainToolWin = null;
        private static Frm_Main m_Frm_Main = null;
       
        public static int m_nDfuColWidth = 70;
        public static Dictionary<string, Dictionary<string, string>> m_dicFormText2FormTypeName = new Dictionary<string, Dictionary<string, string>>();
        private List<FunctionInfo> m_lstOneLevelFunRuntime = new List<FunctionInfo>();
        private WHC.Security.BLL.Function function = new WHC.Security.BLL.Function();
        public static int m_nLoginUserId = 0;
        private static TrainingDB.BLL.CK_OperLogTab m_bllDG_OperLogTab = new TrainingDB.BLL.CK_OperLogTab();
        public static Dictionary<string, string> m_dicModuleHelpWnd = new Dictionary<string, string>();
        private static List<FunctionInfo> m_UserFunList = new List<FunctionInfo>();

        public static bool CheckPerm(string strModuleName, string strOperName)
        {
            bool bRet = false;
            string strTemp = strModuleName + "_" + strOperName;
            foreach (FunctionInfo f in m_UserFunList)
            {
                if (f.Name.Equals(strTemp))
                {
                    bRet = true;
                    break;
                }
            }
            return bRet;
        }
        public Frm_Main()
        {
            InitializeComponent();
            InitFormText2FormType();
            InitModuleHelpWnd();
            InitFirstLevelFun();
            InitSecondLevelFun();
        
        }
        void tsb_Click(object sender, EventArgs e)
        {
            ToolStripButton tsmi = (ToolStripButton)sender;
            ShowContent(tsmi.Text.ToString());
            return;
        }
        private void InitToolStrip()
        {
            int nIndex = 0;
            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                //ToolStrip ts = new ToolStrip();
                ToolStripButton tsb = new ToolStripButton(strModule);
                tsb.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                tsb.Image = this.imageList1.Images[nIndex++];//从ImageList里指定或其他方式指定
                tsb.Click += new EventHandler(tsb_Click);
                toolStrip1.Items.Add(tsb);
            }

        }

        private void InitMenuItem()
        {
            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Name = strModule; //menuname
                item.Text = strModule;
                //menuStrip1.Items[item.Name].Enabled = true;
                InitSubMenuItem(item);
                menuStrip1.Items.Add(item);
            }

        }
        private void InitSubMenuItem(ToolStripItem item)
        {
            string mname = item.Name;
            ToolStripMenuItem pItem = (ToolStripMenuItem)item;
            //根据父菜单项加载子菜单

           
            foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[mname].Keys)
            {
                try
                {
                    ToolStripMenuItem subItem = new ToolStripMenuItem();
                    subItem.Name = strItem; //menuname
                    subItem.Text = strItem;
                    subItem.Click += new EventHandler(subItem_Click);
                    pItem.DropDownItems.Add(subItem);
                    //pItem.DropDownItems[strItem].Enabled = true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }

        }
        void subItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            ShowContent(tsmi.Text.ToString());
            return;
        }
        public static void Log2DB(string strModuleName, string strOperName, string DanjuNameOrNo)
        {
            TrainingDB.Model.CK_OperLogTab modelCK_OperLogTab = new TrainingDB.Model.CK_OperLogTab();
            modelCK_OperLogTab.CK_OperDate = System.DateTime.Now;
            modelCK_OperLogTab.CK_OperUserID = m_nLoginUserId;
            modelCK_OperLogTab.CK_OperName = strOperName;
            modelCK_OperLogTab.CK_ModuleName = strModuleName;
            modelCK_OperLogTab.CK_DanjuNameOrNo = DanjuNameOrNo;

            m_bllDG_OperLogTab.Add(modelCK_OperLogTab);
        }
        private void InitModuleHelpWnd()
        {
            m_dicModuleHelpWnd.Add("教学管理", "CKNetFrameWork.Frm_EducationMgr");
            m_dicModuleHelpWnd.Add("主页", "CKNetFrameWork.Frm_Home");
        }
        private void InitFormText2FormType()
        {
            Dictionary<string, string> dicCSharpBase = new Dictionary<string, string>();
            dicCSharpBase.Add("教室管理", "CKNetFrameWork.Frm_ClassRoomEx");
            dicCSharpBase.Add("课程管理", "CKNetFrameWork.Frm_Course");
            dicCSharpBase.Add("班级管理", "CKNetFrameWork.Frm_ClassMgr");
            dicCSharpBase.Add("班级排课管理", "CKNetFrameWork.Frm_ClassPrdSchd");
            dicCSharpBase.Add("课程表", "CKNetFrameWork.Frm_ClassTable");
            dicCSharpBase.Add("排课明细管理", "CKNetFrameWork.Frm_ClassPrdSchdDetail");
            
            //dicCSharpBase.Add("教室管理分页", "CKNetFrameWork.Frm_ClassRoomPager");
            //dicCSharpBase.Add("教室管理分页1", "CKNetFrameWork.Frm_ClassRoomPager1");
            //dicCSharpBase.Add("零售商管理", "CKNetFrameWork.Frm_Seller");
            m_dicFormText2FormTypeName.Add("教学管理", dicCSharpBase);

            Dictionary<string, string> dicCSharpStore = new Dictionary<string, string>();
            dicCSharpStore.Add("校区管理", "CKNetFrameWork.Frm_SchoolEx");
            dicCSharpStore.Add("教师管理", "CKNetFrameWork.Frm_Teacher");
            dicCSharpStore.Add("时段管理", "CKNetFrameWork.Frm_TimeSeg");
            dicCSharpStore.Add("上课方式管理", "CKNetFrameWork.Frm_ClassWay");
            dicCSharpStore.Add("信息来源管理", "CKNetFrameWork.Frm_InfoFrom");
            dicCSharpStore.Add("意向程度管理", "CKNetFrameWork.Frm_IntentionDegree");
            dicCSharpStore.Add("咨询方式管理", "CKNetFrameWork.Frm_ConsultWay");
            dicCSharpStore.Add("支付方式管理", "CKNetFrameWork.Frm_PayWay");
            dicCSharpStore.Add("银行账户管理", "CKNetFrameWork.Frm_BankAccount");
            dicCSharpStore.Add("其他收费项目", "CKNetFrameWork.Frm_OtherFeeItem");
            dicCSharpStore.Add("收费模式管理", "CKNetFrameWork.Frm_RecvMoneyWay");
            m_dicFormText2FormTypeName.Add("基本信息", dicCSharpStore);

            Dictionary<string, string> dicCSharpStudent = new Dictionary<string, string>();
            dicCSharpStudent.Add("咨询登记", "CKNetFrameWork.Frm_ConsultReg");
            dicCSharpStudent.Add("报名登记", "CKNetFrameWork.Frm_StudentEnterReg");
            dicCSharpStudent.Add("收费单", "CKNetFrameWork.Frm_PayIn");
            dicCSharpStudent.Add("班级考勤登记", "CKNetFrameWork.Frm_StudAtt");
            dicCSharpStudent.Add("学费到期催款", "CKNetFrameWork.Frm_feeExpireNotice");
            m_dicFormText2FormTypeName.Add("学员管理", dicCSharpStudent);
            
            Dictionary<string, string> dicCSharpData = new Dictionary<string, string>();
            dicCSharpData.Add("操作日志", "CKNetFrameWork.Frm_OperLog");
            m_dicFormText2FormTypeName.Add("数据管理", dicCSharpData);
        }
        //初始化一次每次新增模块时调用
        private void InitFirstLevelFun()
        {
 
            List<FunctionInfo> list = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetAllFirstLevelFunctions();
            List<string> listName = new List<string>();
            foreach(FunctionInfo f in list)
            {
                listName.Add(f.Name);
            }
            foreach (string strTemp in m_dicFormText2FormTypeName.Keys)
            {
                if (listName.Contains(strTemp))
                    continue;
                FunctionInfo info = new FunctionInfo();
                info.Name = strTemp;
                info.PID = -1;
                info.ControlID = "";
                info.SystemType_ID = "WareMis";
                function.Insert(info);
            }
        }
        //初始化一次每次新增模块时调用
        private void InitSecondLevelFun()
        {


            List<FunctionInfo> list = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetAllFunctions();
            List<string> listName = new List<string>();
            foreach (FunctionInfo f in list)
            {
                listName.Add(f.Name);
            }

            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                FunctionInfo fi = function.FindSingle("name='" + strModule+"'");
                foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[strModule].Keys)
                {
                    if (listName.Contains(strItem))
                        continue;
                    FunctionInfo info = new FunctionInfo();
                    info.Name = strItem;
                    info.PID = fi.ID;
                    info.ControlID = Frm_Main.m_dicFormText2FormTypeName[strModule][strItem];
                    info.SystemType_ID = "WareMis";
                    int nID = function.Insert2(info);

                    FunctionInfo infoAdd = new FunctionInfo();
                    infoAdd.Name = strItem + "_增加";
                    infoAdd.PID = nID;
                    infoAdd.ControlID = "";
                    infoAdd.SystemType_ID = "WareMis";
                    function.Insert(infoAdd);

                    FunctionInfo infoMod = new FunctionInfo();
                    infoMod.Name = strItem + "_修改";
                    infoMod.PID = nID;
                    infoMod.ControlID = "";
                    infoMod.SystemType_ID = "WareMis";
                    function.Insert(infoMod);

                    FunctionInfo infoDel = new FunctionInfo();
                    infoDel.Name = strItem + "_删除";
                    infoDel.PID = nID;
                    infoDel.ControlID = "";
                    infoDel.SystemType_ID = "WareMis";
                    function.Insert(infoDel);
                }
            }
        }
        private string GetParentName(FunctionInfo functionInfoChild)
        {
            foreach (FunctionInfo functionInfo in m_lstOneLevelFunRuntime)
            {
                if (functionInfo.ID == functionInfoChild.PID)
                {
                    return functionInfo.Name;
                }
            }
            return "";
        }
        private void InitFormText2FormTypeNameDic()
        {
            m_lstOneLevelFunRuntime.Clear();
            m_dicFormText2FormTypeName.Clear();
            m_UserFunList = WHC.Security.BLL.BLLFactory<WHC.Security.BLL.Function>.Instance.GetFunctionsByUser(m_nLoginUserId, "WareMis");

            if (m_UserFunList != null && m_UserFunList.Count > 0)
            {

                foreach (FunctionInfo functionInfo in m_UserFunList)
                {
                    if (functionInfo.PID == -1)
                    {
                        Dictionary<string, string> dicCSharpBase = new Dictionary<string, string>();
                        m_dicFormText2FormTypeName.Add(functionInfo.Name, dicCSharpBase);
                        m_lstOneLevelFunRuntime.Add(functionInfo);
                    }
                }

                foreach (FunctionInfo functionInfoFather in m_lstOneLevelFunRuntime)
                {
                    foreach (FunctionInfo functionInfo in m_UserFunList)
                    {
                        if (functionInfo.PID == functionInfoFather.ID)
                        {
                            
                            //string strTemp = GetParentName(functionInfo);
                            if (m_dicFormText2FormTypeName.Keys.Contains(functionInfoFather.Name))
                                m_dicFormText2FormTypeName[functionInfoFather.Name].Add(functionInfo.Name, functionInfo.ControlID);
                               

                        }
                    }
                }

            }

            return;
           
            
        }
        public static Frm_Main GetMainForm()
        {
            if (m_Frm_Main == null)
            {
                m_Frm_Main = new Frm_Main();
            }

            return m_Frm_Main;
        }
        private DockContent FindDocument(string text)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.DockingMdi)
            {
                foreach (Form form in MdiChildren)
                {
                    if (form.Text == text)
                    {
                        return form as DockContent;
                    }
                }

                return null;
            }
            else
            {
                foreach (DockContent content in dockPanel.Documents)
                {
                    if (content.DockHandler.TabText == text)
                    {
                        return content;
                    }
                }

                return null;
            }
        }

        public void ShowContent(DockContent frm)
        {
            frm.Show(this.dockPanel);
            frm.Focus();
            frm.BringToFront();
        }
        private string GetClassByName(string strName)
        {
            string strTemp = "";
            foreach (string strModule in Frm_Main.m_dicFormText2FormTypeName.Keys)
            {
                foreach (string strItem in Frm_Main.m_dicFormText2FormTypeName[strModule].Keys)
                {
                    if (strItem == strName)
                    {
                        strTemp = Frm_Main.m_dicFormText2FormTypeName[strModule][strItem];
                        break;
                    }
                }
            }
            foreach (string strItem in Frm_Main.m_dicModuleHelpWnd.Keys)
            {
                if (strItem == strName)
                {
                    strTemp = Frm_Main.m_dicModuleHelpWnd[strItem];
                    break;
                }
            }
            return strTemp;
        }

        private bool HaveFun(string strTemp)
        {
            bool bRet = false;
            if(m_dicModuleHelpWnd.Keys.Contains(strTemp))
            {
                return true;
            }

            foreach (string strModule in m_dicFormText2FormTypeName.Keys)
            {
            
                if (m_dicFormText2FormTypeName[strModule].Keys.Contains(strTemp))
                {
                    bRet = true;
                    break;
                }
              
            }
            return bRet;
        }

        private Object ShowContentEx(string strTemp)
        {
            string[] strSplit = strTemp.Split('.');
            string strAssemblyName = strSplit[0];

            Assembly assembly = Assembly.Load(strAssemblyName);
            //test(assembly);

            Type typForm = assembly.GetType(strTemp);
            //关于InvokeMember用法，不明白的可以查看：http://msdn.microsoft.com/zh-cn/library/de3dhzwy(VS.80).aspx
            Object mdiChild = typForm.InvokeMember(
               null,
                BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance,
               null,
               null,
               null);

            return mdiChild;
        }
        private Object ShowContentEx2(string strTemp)
        {
            string[] strSplit = strTemp.Split('.');
            string strAssemblyName = strSplit[0];
            Object mdiChild = null;
            switch (strSplit[1])
            {
                case "Frm_EducationMgr":
                    {
                        mdiChild = new Frm_EducationMgr();
                        break;
                    }
                case "Frm_Home":
                    {
                        mdiChild = new Frm_Home();
                        break;
                    }
                case "Frm_ClassRoomEx":
                    {
                        mdiChild = new Frm_ClassRoomEx();
                        break;
                    }
                case "Frm_Course":
                    {
                        mdiChild = new Frm_Course();
                        break;
                    }
                case "Frm_ClassMgr":
                    {
                        mdiChild = new Frm_ClassMgr();
                        break;
                    }
                case "Frm_ClassPrdSchd":
                    {
                        mdiChild = new Frm_ClassPrdSchd();
                        break;
                    }
                case "Frm_ClassTable":
                    {
                        mdiChild = new Frm_ClassTable();
                        break;
                    }
                case "Frm_ClassPrdSchdDetail":
                    {
                        mdiChild = new Frm_ClassPrdSchdDetail();
                        break;
                    }
                case "Frm_SchoolEx":
                    {
                        mdiChild = new Frm_SchoolEx();
                        break;
                    }
                case "Frm_Teacher":
                    {
                        mdiChild = new Frm_Teacher();
                        break;
                    }
                case "Frm_TimeSeg":
                    {
                        mdiChild = new Frm_TimeSeg();
                        break;
                    }
                case "Frm_ClassWay":
                    {
                        mdiChild = new Frm_ClassWay();
                        break;
                    }
                case "Frm_InfoFrom":
                    {
                        mdiChild = new Frm_InfoFrom();
                        break;
                    }
                case "Frm_IntentionDegree":
                    {
                        mdiChild = new Frm_IntentionDegree();
                        break;
                    }
                case "Frm_ConsultWay":
                    {
                        mdiChild = new Frm_ConsultWay();
                        break;
                    }
                case "Frm_PayWay":
                    {
                        mdiChild = new Frm_PayWay();
                        break;
                    }
                case "Frm_BankAccount":
                    {
                        mdiChild = new Frm_BankAccount();
                        break;
                    }
                case "Frm_OtherFeeItem":
                    {
                        mdiChild = new Frm_OtherFeeItem();
                        break;
                    }
                case "Frm_RecvMoneyWay":
                    {
                        mdiChild = new Frm_RecvMoneyWay();
                        break;
                    }
                case "Frm_ConsultReg":
                    {
                        mdiChild = new Frm_ConsultReg();
                        break;
                    }
                case "Frm_StudentEnterReg":
                    {
                        mdiChild = new Frm_StudentEnterReg();
                        break;
                    }
                case "Frm_PayIn":
                    {
                        mdiChild = new Frm_PayIn();
                        break;
                    }
                case "Frm_StudAtt":
                    {
                        mdiChild = new Frm_StudAtt();
                        break;
                    }
                case "Frm_feeExpireNotice":
                    {
                        mdiChild = new Frm_feeExpireNotice();
                        break;
                    }
                case "Frm_OperLog":
                    {
                        mdiChild = new Frm_OperLog();
                        break;
                    }
                default:
                    break;
            }

            //Assembly assembly = Assembly.Load(strAssemblyName);
            ////test(assembly);

            //Type typForm = assembly.GetType(strTemp);
            ////关于InvokeMember用法，不明白的可以查看：http://msdn.microsoft.com/zh-cn/library/de3dhzwy(VS.80).aspx
            //Object mdiChild = typForm.InvokeMember(
            //   null,
            //    BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance,
            //   null,
            //   null,
            //   null);

            return mdiChild;
        }
        public DockContent ShowContent(string caption/*, Type formType*/)
        {

            DockContent frm = FindDocument(caption);

            if (frm == null)
            {
                //DockContent currentMdiChild = null;
                //Assembly assembly = Assembly.GetExecutingAssembly();
                //if (!m_dicFormText2FormTypeName.ContainsKey(caption))
                //    return frm;
                //Type typForm = assembly.GetType(m_dicFormText2FormTypeName[caption]);
                if (!HaveFun(caption))
                    return null;
                string strTemp = GetClassByName(caption);
                if (strTemp == "")
                    return null;


                Object mdiChild = ShowContentEx2(strTemp);

                if (mdiChild != null)
                {
                    frm = mdiChild as DockContent;
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;

                }
            }

            frm.Show(this.dockPanel);
            frm.Focus();
            frm.BringToFront();
            return frm;
        }
        private void Frm_Main_Load(object sender, EventArgs e)
        {
            //Frm_CourseArrangeSel f = new Frm_CourseArrangeSel();
            //f.ShowDialog();
            try
            {
                
   
                Frm_Login frm_login = new Frm_Login();

                if (frm_login.ShowDialog() == DialogResult.OK)
                {
                    int a = 0;
                }
                else
                {
                    int b = 0;
                    Application.Exit();
                    return;
                }
                InitFormText2FormTypeNameDic();//获取权限
                if (Frm_Main.m_dicFormText2FormTypeName.Count != 0)
                {
                    mainToolWin = new Frm_MainToolWindow();
                    mainToolWin.Show(this.dockPanel, DockState.DockLeft);
                    InitMenuItem();
                    InitToolStrip();
                   
                }

                

                this.dockPanel.DockLeftPortion = 0.17;
                ShowContent("主页");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return ;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            WHC.Security.UI.Portal.StartLogin();
        }

        private void rectangleShape1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonCloseAll_Click(object sender, EventArgs e)
        {
            foreach (Form mdiChildFrm in this.MdiChildren)
            {
                mdiChildFrm.Close();
            }
        }

        private void toolStripButtonHelp_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, Frm_Main.m_strHelpPath, Frm_Main.m_Navigator);
        }

        private void toolStripButtonExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Environment.Exit(1);//退出程序
        }

        private void toolStripButtonAbout_Click(object sender, EventArgs e)
        {
            frmAbout f = new frmAbout();
            f.ShowDialog();
            f.Dispose();
        }

        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Close();
            Environment.Exit(1);
            return;
        }
    }
}
